<?php
/**
 * Product: ASW.Communication.
 * Date: 2024-05-16
 * Time: 12:12
 */

require '../vendor/autoload.php';

use ASW\Communication\EventChannelClient;
use Workerman\Timer;

function writeLog(string $content): void
{
    $timeStr = date('Y-m-d H:i:s');
    echo "$timeStr $content" . PHP_EOL;
}

$publishTimer = 0;
$worker = new \Workerman\Worker();
$worker->onWorkerStart = function () {

    // 创建客户端
    $eventChannelClient = new EventChannelClient();

    // 连接
    $eventChannelClient->onConnected(function (EventChannelClient $eventChannelClient) {
        writeLog("client connected");

        // 连接后，每隔5秒发布一次事件
        Timer::add(5, function () use ($eventChannelClient) {
            $eventChannelClient->publish('test', ['from' => 'channel_client', 'time' => time()]);
            writeLog("publish");
        });
    });

    $eventChannelClient->onClosed(function (EventChannelClient $eventChannelClient) {
        writeLog("client closed");
    });

    $eventChannelClient->connect();
};

\Workerman\Worker::runAll();